package com.zhentao.engine.impl;

import com.zhentao.engine.RuleEngine;
import com.zhentao.enums.RuleExecuteStatusEnum;
import com.zhentao.pojo.ParamRule;
import com.zhentao.vo.RuleExecuteResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * 正则表达式规则引擎
 * @author zhentao
 * @date 2024-12-19
 */
@Slf4j
@Component
public class RegexRuleEngine implements RuleEngine {

    @Override
    public RuleExecuteResultVO executeRule(ParamRule rule, Map<String, Object> inputData, Map<String, Object> context) {
        RuleExecuteResultVO result = new RuleExecuteResultVO();
        Date startTime = new Date();
        
        try {
            String regexPattern = rule.getConditionExpression();
            if (regexPattern == null || regexPattern.trim().isEmpty()) {
                result.setStatus(RuleExecuteStatusEnum.PARAM_ERROR.getCode());
                result.setMessage("正则表达式为空");
                return result;
            }
            
            // 获取待匹配的文本（从输入数据中获取）
            String inputText = getInputText(inputData);
            if (inputText == null) {
                result.setStatus(RuleExecuteStatusEnum.PARAM_ERROR.getCode());
                result.setMessage("未找到待匹配的文本，请在输入数据中提供 'text' 字段");
                return result;
            }
            
            // 编译正则表达式
            Pattern pattern = Pattern.compile(regexPattern);
            Matcher matcher = pattern.matcher(inputText);
            
            // 执行匹配
            Map<String, Object> resultData = new HashMap<>();
            resultData.put("pattern", regexPattern);
            resultData.put("inputText", inputText);
            resultData.put("matches", matcher.matches());
            resultData.put("find", matcher.find());
            
            // 重置matcher进行group捕获
            matcher.reset();
            if (matcher.find()) {
                resultData.put("groupCount", matcher.groupCount());
                
                // 提取所有匹配组
                Map<String, String> groups = new HashMap<>();
                for (int i = 0; i <= matcher.groupCount(); i++) {
                    groups.put("group" + i, matcher.group(i));
                }
                resultData.put("groups", groups);
            }
            
            result.setStatus(RuleExecuteStatusEnum.SUCCESS.getCode());
            result.setMessage("正则表达式执行成功");
            result.setResultData(resultData);
            
            log.debug("正则规则执行成功: {} 匹配 {}", regexPattern, inputText);
            
        } catch (PatternSyntaxException e) {
            result.setStatus(RuleExecuteStatusEnum.ERROR.getCode());
            result.setMessage("正则表达式语法错误: " + e.getMessage());
            result.setErrorCode("REGEX_SYNTAX_ERROR");
            result.setErrorDetail(e.toString());
            log.error("正则规则语法错误: {}", rule.getRuleCode(), e);
        } catch (Exception e) {
            result.setStatus(RuleExecuteStatusEnum.ERROR.getCode());
            result.setMessage("正则规则执行失败: " + e.getMessage());
            result.setErrorDetail(e.toString());
            log.error("正则规则执行失败: {}", rule.getRuleCode(), e);
        } finally {
            result.setEndTime(new Date());
            result.setExecutionTime(result.getEndTime().getTime() - startTime.getTime());
        }
        
        return result;
    }

    @Override
    public String validateRuleSyntax(String ruleContent, String engineType) {
        try {
            if (ruleContent == null || ruleContent.trim().isEmpty()) {
                return "正则表达式不能为空";
            }
            
            // 尝试编译正则表达式
            Pattern.compile(ruleContent);
            
            // 语法检查通过
            return null;
            
        } catch (PatternSyntaxException e) {
            return "正则表达式语法错误: " + e.getMessage();
        } catch (Exception e) {
            return "正则表达式校验失败: " + e.getMessage();
        }
    }

    @Override
    public String getSupportedEngineType() {
        return "REGEX";
    }

    @Override
    public int getPriority() {
        return 90; // 较高优先级
    }
    
    /**
     * 从输入数据中获取待匹配的文本
     */
    private String getInputText(Map<String, Object> inputData) {
        if (inputData == null) {
            return null;
        }
        
        // 优先使用 'text' 字段
        Object textObj = inputData.get("text");
        if (textObj != null) {
            return textObj.toString();
        }
        
        // 尝试其他常见字段名
        String[] possibleKeys = {"value", "content", "input", "data", "str", "string"};
        for (String key : possibleKeys) {
            Object obj = inputData.get(key);
            if (obj != null) {
                return obj.toString();
            }
        }
        
        // 如果只有一个字段，直接使用它
        if (inputData.size() == 1) {
            Object value = inputData.values().iterator().next();
            return value != null ? value.toString() : null;
        }
        
        return null;
    }
}

